# -*- coding: utf-8 -*-
import json
import os
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("convert_diabetes_fields")

# 文件路径
current_dir = os.path.dirname(os.path.abspath(__file__))
knowledge_path = os.path.join(current_dir, 'knowledge.json')

# 糖尿病数据集字段说明
diabetes_fields = [
    {"field": "PatientID", "description": "患者ID"},
    {"field": "Age", "description": "年龄（岁）"},
    {"field": "Gender", "description": "性别，0：男，1：女"},
    {"field": "Ethnicity", "description": "种族，0：白种人，1：非裔美国人，2：亚洲人，3：其他"},
    {"field": "SocioeconomicStatus", "description": "社会经济地位，0：低，1：中，2：高"},
    {"field": "EducationLevel", "description": "教育水平，0：无，1：高中，2：学士学位，3：更高"},
    {"field": "BMI", "description": "体质指数（体重(kg)/身高(m)^2）"},
    {"field": "Smoking", "description": "吸烟状况"},
    {"field": "AlcoholConsumption", "description": "饮酒量"},
    {"field": "PhysicalActivity", "description": "每周体育活动时间（分钟）"},
    {"field": "DietQuality", "description": "饮食质量"},
    {"field": "SleepQuality", "description": "睡眠质量"},
    {"field": "FamilyHistoryDiabetes", "description": "家族糖尿病史"},
    {"field": "GestationalDiabetes", "description": "妊娠糖尿病"},
    {"field": "PolycysticOvarySyndrome", "description": "多囊卵巢综合症"},
    {"field": "PreviousPreDiabetes", "description": "既往糖尿病前期"},
    {"field": "Hypertension", "description": "高血压"},
    {"field": "SystolicBP", "description": "收缩压（mm Hg）"},
    {"field": "DiastolicBP", "description": "舒张压（mm Hg）"},
    {"field": "FastingBloodSugar", "description": "空腹血糖浓度"},
    {"field": "HbA1c", "description": "糖化血红蛋白"},
    {"field": "SerumCreatinine", "description": "血清肌酐"},
    {"field": "BUNLevels", "description": "血尿素氮"},
    {"field": "CholesterolTotal", "description": "总胆固醇水平"},
    {"field": "CholesterolLDL", "description": "低密度脂蛋白胆固醇水平"},
    {"field": "CholesterolHDL", "description": "高密度脂蛋白胆固醇水平"},
    {"field": "CholesterolTriglycerides", "description": "甘油三酯"},
    {"field": "AntihypertensiveMedications", "description": "降压药使用情况"},
    {"field": "Statins", "description": "他汀类药物使用情况"},
    {"field": "AntidiabeticMedications", "description": "降糖药物使用情况"},
    {"field": "FrequentUrination", "description": "尿频"},
    {"field": "ExcessiveThirst", "description": "过度口渴"},
    {"field": "UnexplainedWeightLoss", "description": "不明原因的体重减轻"},
    {"field": "FatigueLevels", "description": "疲劳水平"},
    {"field": "BlurredVision", "description": "视力模糊"},
    {"field": "SlowHealingSores", "description": "伤口愈合缓慢"},
    {"field": "TinglingHandsFeet", "description": "手脚刺痛"},
    {"field": "QualityOfLifeScore", "description": "生活质量评分"},
    {"field": "HeavyMetalsExposure", "description": "重金属暴露情况"},
    {"field": "OccupationalExposureChemicals", "description": "职业化学品暴露情况"},
    {"field": "WaterQuality", "description": "水质是否存在污染"},
    {"field": "MedicalCheckupsFrequency", "description": "定期体检频率"},
    {"field": "MedicationAdherence", "description": "药物依从性"},
    {"field": "HealthLiteracy", "description": "健康素养"},
    {"field": "Diagnosis", "description": "糖尿病诊断（0=否，1=是）"},
    {"field": "DoctorInCharge", "description": "主管医生"}
]

def load_existing_knowledge():
    """加载现有的知识库文件"""
    if os.path.exists(knowledge_path):
        try:
            with open(knowledge_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except json.JSONDecodeError:
            logger.error("知识库文件格式错误，将创建新文件")
            return []
        except Exception as e:
            logger.error(f"读取知识库文件时出错: {e}")
            return []
    else:
        logger.info("知识库文件不存在，将创建新文件")
        return []

def convert_to_knowledge_entries():
    """将糖尿病数据集字段信息转换为知识条目"""
    try:
        # 加载现有知识条目
        knowledge_data = load_existing_knowledge()
        initial_count = len(knowledge_data)
        logger.info(f"已加载现有知识库，包含 {initial_count} 条知识条目")
        
        # 获取最大ID
        max_id = 0
        if knowledge_data:
            try:
                max_id = max(item['id'] for item in knowledge_data)
            except KeyError:
                logger.warning("现有知识条目中没有id字段，将从1开始编号")
        
        # 创建知识条目
        new_entries = []
        
        # 1. 创建总体介绍知识条目
        max_id += 1
        general_intro = {
            "id": max_id,
            "text": "糖尿病数据集字段说明\n\n该数据集包含患者的基本信息（如年龄、性别、种族）、生活习惯（如吸烟、饮酒、体育活动）、体检指标（如BMI、血压、血糖）、糖尿病相关症状（如尿频、口渴、视力模糊）等46个字段，用于糖尿病风险评估和预测。\n\n关键词：糖尿病 数据集 字段 医疗数据 风险因素 健康指标 预测模型"
        }
        new_entries.append(general_intro)
        
        # 2. 按分类创建知识条目
        categories = {
            "基本信息": ["PatientID", "Age", "Gender", "Ethnicity", "SocioeconomicStatus", "EducationLevel", "DoctorInCharge"],
            "生活习惯": ["BMI", "Smoking", "AlcoholConsumption", "PhysicalActivity", "DietQuality", "SleepQuality"],
            "医疗史": ["FamilyHistoryDiabetes", "GestationalDiabetes", "PolycysticOvarySyndrome", "PreviousPreDiabetes", "Hypertension"],
            "体检指标": ["SystolicBP", "DiastolicBP", "FastingBloodSugar", "HbA1c", "SerumCreatinine", "BUNLevels", "CholesterolTotal", "CholesterolLDL", "CholesterolHDL", "CholesterolTriglycerides"],
            "用药情况": ["AntihypertensiveMedications", "Statins", "AntidiabeticMedications", "MedicationAdherence"],
            "症状表现": ["FrequentUrination", "ExcessiveThirst", "UnexplainedWeightLoss", "FatigueLevels", "BlurredVision", "SlowHealingSores", "TinglingHandsFeet", "QualityOfLifeScore"],
            "环境因素": ["HeavyMetalsExposure", "OccupationalExposureChemicals", "WaterQuality"],
            "健康管理": ["MedicalCheckupsFrequency", "HealthLiteracy"],
            "诊断结果": ["Diagnosis"]
        }
        
        # 为每个分类创建知识条目
        for category, fields in categories.items():
            max_id += 1
            category_fields = [f"{field} ({next((item['description'] for item in diabetes_fields if item['field'] == field), '未知')}" for field in fields]
            
            category_text = f"糖尿病数据集 - {category}字段说明\n\n"
            category_text += "\n".join([f"• {field}" for field in category_fields])
            category_text += f"\n\n关键词：糖尿病 {category} 医疗数据 健康指标"
            
            new_entries.append({
                "id": max_id,
                "text": category_text
            })
        
        # 3. 为每个字段创建单独的知识条目
        for field_info in diabetes_fields:
            max_id += 1
            field = field_info["field"]
            description = field_info["description"]
            
            # 确定该字段属于哪个分类
            category = ""
            for cat, fields in categories.items():
                if field in fields:
                    category = cat
                    break
            
            field_text = f"糖尿病数据集字段：{field}\n\n"
            field_text += f"描述：{description}\n"
            field_text += f"分类：{category}\n"
            
            # 为特定字段添加更详细的说明
            if field == "BMI":
                field_text += "\nBMI是体质指数(Body Mass Index)的缩写，计算公式为体重(kg)除以身高(m)的平方。BMI<18.5为偏瘦，18.5≤BMI<24为正常，24≤BMI<28为超重，BMI≥28为肥胖。肥胖是糖尿病的重要风险因素。"
            elif field == "HbA1c":
                field_text += "\n糖化血红蛋白(HbA1c)反映近2-3个月的平均血糖水平，是诊断糖尿病的重要指标。正常人HbA1c<5.7%，5.7%≤HbA1c<6.5%为糖尿病前期，HbA1c≥6.5%可诊断为糖尿病。"
            elif field == "FastingBloodSugar":
                field_text += "\n空腹血糖是评估糖代谢状态的基本指标。正常空腹血糖<5.6mmol/L(100mg/dL)，5.6-6.9mmol/L(100-125mg/dL)为空腹血糖受损(IFG)，≥7.0mmol/L(126mg/dL)可诊断为糖尿病。"
            
            field_text += f"\n\n关键词：糖尿病 {field} {description.split('，')[0]} 健康指标 医疗数据"
            
            new_entries.append({
                "id": max_id,
                "text": field_text
            })
        
        # 4. 创建糖尿病风险因素和预防知识条目
        max_id += 1
        risk_factors = {
            "id": max_id,
            "text": "糖尿病风险因素\n\n以下因素会增加患糖尿病的风险：\n• 超重和肥胖(高BMI)\n• 年龄增长\n• 家族糖尿病史\n• 高血压\n• 不健康的饮食习惯\n• 缺乏体育活动\n• 妊娠糖尿病史\n• 多囊卵巢综合症\n• 高胆固醇和高甘油三酯\n• 种族因素(某些种族如非裔美国人风险更高)\n\n关键词：糖尿病 风险因素 预防 肥胖 高血压 家族史"
        }
        new_entries.append(risk_factors)
        
        max_id += 1
        symptoms = {
            "id": max_id,
            "text": "糖尿病常见症状\n\n糖尿病的典型症状包括：\n• 尿频(FrequentUrination)\n• 过度口渴(ExcessiveThirst)\n• 不明原因的体重减轻(UnexplainedWeightLoss)\n• 持续疲劳(FatigueLevels)\n• 视力模糊(BlurredVision)\n• 伤口愈合缓慢(SlowHealingSores)\n• 手脚刺痛(TinglingHandsFeet)\n\n这些症状往往在血糖水平明显升高时出现，但2型糖尿病患者可能长期无明显症状。\n\n关键词：糖尿病 症状 尿频 口渴 体重减轻 疲劳 视力模糊"
        }
        new_entries.append(symptoms)
        
        # 添加到知识库
        knowledge_data.extend(new_entries)
        logger.info(f"已创建 {len(new_entries)} 条新知识条目")
        
        # 保存更新后的知识库
        with open(knowledge_path, 'w', encoding='utf-8') as f:
            json.dump(knowledge_data, f, ensure_ascii=False, indent=2)
        
        logger.info(f"知识库已更新，当前共有 {len(knowledge_data)} 条知识条目")
        logger.info(f"新增 {len(knowledge_data) - initial_count} 条知识条目")
        
        # 打印一条示例条目
        if new_entries:
            logger.info(f"示例条目: {new_entries[0]['text'][:200]}...")
        
        return True
    
    except Exception as e:
        logger.error(f"转换过程中出错: {e}")
        import traceback
        logger.error(traceback.format_exc())
        return False

if __name__ == "__main__":
    logger.info("开始转换糖尿病数据集字段信息到知识库")
    success = convert_to_knowledge_entries()
    if success:
        logger.info("转换完成")
    else:
        logger.error("转换失败") 